// 图片预加载系统 - 现在使用粒子系统
class ImagePreloader {
    constructor() {
        this.imageList = [
            'images/placeholder.svg',
            'images/lab_night.svg',
            'images/data_screen.svg',
            'images/blue_glow.svg',
            'images/emergency_shutdown.svg',
            'images/scientific_discovery.svg',
            'images/portal_opened.svg',
            'images/time_fusion.svg',
            'images/observer_effect.svg',
            'images/team_safety.svg',
            'images/parallel_world.svg'
        ];
        this.loadedImages = new Map();
        this.fallbackImage = 'images/placeholder.svg';
        this.useParticleSystem = true; // 启用粒子系统
    }

    // 预加载所有图片
    async preloadImages() {
        if (this.useParticleSystem && window.particleImageSystem) {
            console.log('🎨 粒子图片系统已激活，跳过传统图片预加载');
            
            // 预生成一些常用的粒子画布
            const commonScenes = [
                'lab_night', 'data_screen', 'blue_glow', 'emergency_shutdown',
                'scientific_discovery', 'multiverse_portal', 'cosmic_choice'
            ];
            
            commonScenes.forEach(scene => {
                try {
                    const canvas = window.particleImageSystem.createParticleCanvas(`images/${scene}.svg`, 600, 400);
                    this.loadedImages.set(`images/${scene}.svg`, canvas);
                } catch (error) {
                    console.warn(`粒子场景生成失败: ${scene}`, error);
                }
            });
            
            console.log(`✅ 预生成了 ${commonScenes.length} 个粒子场景`);
            return;
        }
        
        console.log('🖼️ 开始预加载图片资源...');
        
        const loadPromises = this.imageList.map(imagePath => {
            return this.loadImage(imagePath);
        });

        try {
            await Promise.allSettled(loadPromises);
            console.log('✅ 图片预加载完成');
        } catch (error) {
            console.warn('⚠️ 部分图片加载失败，将使用占位符', error);
        }
    }

    // 加载单个图片
    loadImage(imagePath) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            
            img.onload = () => {
                this.loadedImages.set(imagePath, img);
                console.log(`✓ 图片加载成功: ${imagePath}`);
                resolve(img);
            };
            
            img.onerror = () => {
                console.warn(`⚠️ 图片加载失败: ${imagePath}`);
                // 使用占位符
                this.loadedImages.set(imagePath, this.fallbackImage);
                resolve(this.fallbackImage);
            };
            
            img.src = imagePath;
        });
    }

    // 获取图片URL，如果不存在则返回占位符
    getImageUrl(imagePath) {
        if (this.useParticleSystem && window.particleImageSystem) {
            // 使用粒子系统，返回空值，让系统自动替换
            return null;
        }
        
        if (this.loadedImages.has(imagePath)) {
            const loadedImage = this.loadedImages.get(imagePath);
            return typeof loadedImage === 'string' ? loadedImage : imagePath;
        }
        return this.fallbackImage;
    }

    // 检查图片是否已加载
    isImageLoaded(imagePath) {
        if (this.useParticleSystem) {
            return true; // 粒子系统总是可用的
        }
        return this.loadedImages.has(imagePath);
    }

    // 创建图片元素
    createImageElement(imagePath, alt = '') {
        if (this.useParticleSystem && window.particleImageSystem) {
            // 返回粒子画布
            const canvas = window.particleImageSystem.createParticleCanvas(imagePath, 600, 400);
            canvas.alt = alt;
            return canvas;
        }
        
        const img = document.createElement('img');
        img.src = this.getImageUrl(imagePath);
        img.alt = alt;
        
        // 添加错误处理
        img.onerror = () => {
            img.src = this.fallbackImage;
        };
        
        return img;
    }

    // 设置背景图片
    setBackgroundImage(element, imagePath) {
        if (this.useParticleSystem && window.particleImageSystem) {
            // 使用粒子系统作为背景
            element.innerHTML = '';
            const canvas = window.particleImageSystem.createParticleCanvas(imagePath, 
                element.offsetWidth || 600, element.offsetHeight || 400);
            canvas.style.position = 'absolute';
            canvas.style.top = '0';
            canvas.style.left = '0';
            canvas.style.width = '100%';
            canvas.style.height = '100%';
            element.style.position = 'relative';
            element.appendChild(canvas);
            return;
        }
        
        const imageUrl = this.getImageUrl(imagePath);
        element.style.backgroundImage = `url("${imageUrl}")`;
        element.style.backgroundSize = 'cover';
        element.style.backgroundPosition = 'center';
        element.style.backgroundRepeat = 'no-repeat';
    }
}

// 创建全局图片预加载器实例
window.imagePreloader = new ImagePreloader();

// 在页面加载时预加载图片
document.addEventListener('DOMContentLoaded', () => {
    if (window.imagePreloader) {
        window.imagePreloader.preloadImages();
    }
});

console.log('🖼️ 图片预加载系统已初始化');